import { roleGet } from "./../../api/user";
import { IUserParams, UserInfoType, userLogin } from "@/api/user";
import { createSlice, Dispatch } from "@reduxjs/toolkit";
import { NavigateFunction } from "react-router-dom";
import store2 from "store2";
// import { Dispatch } from "react-redux";
// import store from "../index";
export interface UserStateType {
  isLogin: boolean;
  isLoading: boolean;
  userInfo: UserInfoType | null;
}
let initialState: UserStateType = {
  isLogin: false,
  isLoading: false,
  userInfo: null,
};
// 尝试提取本地存储
// let info = localStorage.getItem("userInfo");
let info = store2.get("userInfo") || store2.session.get("userInfo");
console.log("userInfo", info);
if (info) {
  initialState.userInfo = info;
  initialState.isLogin = true;
}
const userSlice = createSlice({
  name: "user",
  initialState,
  reducers: {
    loginStart(state) {
      state.isLoading = true;
    },
    loginSuccess(state, action) {
      state.isLoading = false;
      state.isLogin = true;
      console.log("登录成功", action);
      // localStorage.setItem("userInfo", JSON.stringify(action.payload));
      let { userInfo, autoLogin } = action.payload;
      state.userInfo = userInfo;
      let auto = autoLogin ? true : false;
      store2("autoLogin", auto); //为了后续在更新本地用户信息的时候，区分【本地存储】【会话存储】
      if (autoLogin) {
        store2("userInfo", userInfo); //存入localStorage
      } else {
        store2.session("userInfo", userInfo); //存入sessionStorage
      }
    },
    loginFail(state) {
      //登录失败、退出登录
      state.isLoading = false;
      state.isLogin = false;
      state.userInfo = null;
      store2.remove("userInfo");
      store2.session.remove("userInfo");
    },
    loginUpdate(state, action) {
      //更新用户信息
      state.userInfo = action.payload;
      if (store2.get("autoLogin")) {
        store2("userInfo", action.payload); //将新用户信息存入localStorage
      } else {
        store2.session("userInfo", action.payload); //将新用户信息存入sessionStorage
      }
    },
  },
});
export const userLoginAsync = (
  params: IUserParams,
  dispatch: Dispatch,
  navigate: NavigateFunction
) => {
  dispatch(loginStart()); //开启登录
  setTimeout(() => {
    userLogin(params)
      .then(async (res) => {
        let role = await roleGet(res.data.roleId);
        console.log("当前登录用户的权限数据", role);
        dispatch(
          loginSuccess({
            userInfo: { ...res.data, ...role.data },
            autoLogin: params.autoLogin,
          })
        ); //登录成功
        navigate("/");
        // 拓展
        let list = store2.get("userList");
        if (!list) {
          store2("userList", [params]);
        } else {
          list.push(params);
          store2("userList", list);
        }
      })
      .catch((err) => {
        dispatch(loginFail()); //登录失败
      });
  }, 2000);
};
export const { loginStart, loginSuccess, loginFail, loginUpdate } =
  userSlice.actions;
export default userSlice.reducer;
